package com.fr.lintcode;

import java.util.Set;

/**
*作者：furong
*日期：2017年2月6日
*时间：上午10:31:01
*/
public class Q107 {
    /**
     * @param s: A string s
     * @param dict: A dictionary of words dict
     */
    public boolean wordBreak(String s, Set<String> dict) {
        if (s == null || s.length() <= 0) {
            return true;
        }
        if (dict == null || dict.size() <= 0) {
            return false;
        }
        boolean dp[] = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1; i <= s.length(); i++) {
            check(i, s, dict, dp);
        }
        return dp[s.length()];
    }

    private void check(int i, String s, Set<String> dict, boolean[] dp) {
        for (String w : dict) {
            int length = w.length();
            if (i < length) {
                continue;
            }
            dp[i] = dp[i - length] && w.equals(s.substring(i - length, i));
            if (dp[i]) {
                break;
            }
        }
    }
}
